package by.qizer.supercamp.dao;

import by.qizer.supercamp.domain.Auto;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Pribytkoyski Alexey
 *         User: qizer
 *         Date: 04.04.12
 */
@Repository
public class AutoDAOImpl implements AutoDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void addAuto(Auto auto) {
        if (checkAuto(auto)) {
            sessionFactory.getCurrentSession().save(auto);
        }
    }

    @SuppressWarnings("unchecked")
    public List<Auto> listAuto() {
        return sessionFactory.getCurrentSession().createQuery("from Auto").list();
    }

    public void removeAuto(Integer id) {
        Auto auto = (Auto) sessionFactory.getCurrentSession().load(Auto.class, id);
        if (auto != null) {
            sessionFactory.getCurrentSession().delete(auto);
        }
    }


    private Boolean checkAuto(Auto auto) {
        String regNumber = auto.getRegNumber();
        String hql = "from Auto where regNumber='" + regNumber + "'";

        List<Auto> answer = sessionFactory.getCurrentSession().createQuery(hql).list();

        if (answer.isEmpty()) {
            return true;
        }
        return false;
    }
}
